package cn.mju.tankfighterbackend.service

import cn.mju.tankfighterbackend.bean.Authority
import cn.mju.tankfighterbackend.dao.CustomerUserRepository
import cn.mju.tankfighterbackend.entity.CustomerUser
import cn.mju.tankfighterbackend.onFalse
import cn.mju.tankfighterbackend.onTrue
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class CustomerUserService
@Autowired
constructor(

    val passwordEncoder: PasswordEncoder,
    val userRepository: CustomerUserRepository
) {
    @Transactional
    fun getUserIdByUserName(userName: String): Long? {
        return userRepository.getUserByUserName(userName)?.id
    }

    @Transactional
    fun registerUser(userName: String, password: String): Boolean {

        return if (!userRepository.existsByUserName(userName)) {
            val customerUser = CustomerUser()
            customerUser.userName = userName
            customerUser.password = passwordEncoder.encode(password)
            customerUser.addAuthority(Authority.Player.roleStr)
            userRepository.save(customerUser)
            true
        } else {
            false
        }

    }
}